﻿

namespace UBCon.Resources.Effects
{
    public class GrayScaleEffect:System.Windows.Media.Effects.ShaderEffect
    {
        private static System.Windows.Media.Effects.PixelShader pixelShader = new System.Windows.Media.Effects.PixelShader() { UriSource = new System.Uri(@"pack://application:,,,/UBCon.Resources;Component/Effects/GrayscaleEffect.ps") };

        public GrayScaleEffect()
        {
            PixelShader = pixelShader;
            UpdateShaderValue(InputProperty);
            UpdateShaderValue(DesaturationFactorProperty);
        }

        public static readonly System.Windows.DependencyProperty InputProperty = System.Windows.Media.Effects.ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(GrayScaleEffect), 0);

        public System.Windows.Media.Brush Input
        {
            get { return (System.Windows.Media.Brush)GetValue(InputProperty); }
            set { SetValue(InputProperty, value); }
        }

        public static readonly System.Windows.DependencyProperty DesaturationFactorProperty = System.Windows.DependencyProperty.Register("DesaturationFactor",
            typeof(double), typeof(GrayScaleEffect), new System.Windows.UIPropertyMetadata(0.0, PixelShaderConstantCallback(0), CoerceDesaturationFactor));

        public double DesaturationFactor
        {
            get { return (double)GetValue(DesaturationFactorProperty); }
            set { SetValue(DesaturationFactorProperty, value); }
        }

        private static object CoerceDesaturationFactor(System.Windows.DependencyObject d, object value)
        {
            GrayScaleEffect effect = (GrayScaleEffect)d;
            double newFactor = (double)value;
            if (newFactor < 0.0 || newFactor > 1.0)
            {
                return effect.DesaturationFactor;
            }
            return newFactor;
        }
    }
}
